<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddUserDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="RolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['borderBottom','center_col',index1===0?'borderTop':'']"
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限所属列 -->
              <el-col span="5">
                <el-tag closable @close="handleRemoveRoles(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限所属列 -->
              <el-col span="19">
                <el-row v-for="(item2,index2) in item1.children" :key="item2.id">
                  <!-- 二级权限所属列 -->
                  <el-col span="5">
                    <el-tag
                      closable
                      @close="handleRemoveRoles(scope.row,item2.id)"
                      type="success"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限所属列 -->
                  <el-col span="19">
                    <el-tag
                      closable
                      @close="handleRemoveRoles(scope.row,item3.id)"
                      class="MarginBottom"
                      type="danger"
                      v-for="(item3,index3) in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip :enterable="false" effect="dark" content="编辑" placement="top">
              <el-button
                @click="getEditUserInfo(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="small"
              ></el-button>
            </el-tooltip>
            <el-tooltip :enterable="false" effect="dark" content="分配权限" placement="top">
              <el-button
                @click="showRolesDialog(scope.row)"
                type="warning"
                icon="el-icon-share"
                size="small"
              ></el-button>
            </el-tooltip>
            <el-tooltip :enterable="false" effect="dark" content="删除" placement="top">
              <el-button
                @click="handleRemoveUser(scope.row.id)"
                type="danger"
                icon="el-icon-delete"
                size="small"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      @close="handleRolesDialogClose"
      title="用户权限"
      :visible.sync="RolesDialogVisible"
      width="40%"
    >
      <el-tree
        ref="TreeRef"
        node-key="id"
        default-expand-all
        :default-checked-keys="checkedKeys"
        show-checkbox
        :data="RolesTreeData"
        :props="RolesTreeProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleGiveRolesRequest">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      @close="handleEditFormReset"
      title="编辑用户"
      :visible.sync="EditUserDialogVisible"
      width="50%"
    >
      <el-form :model="EditUserForm" :rules="EditUserFormRules" ref="EditUserFormRef">
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="EditUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="EditUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditUserRequest">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      @close="handleAddFormReset"
      title="添加角色"
      :visible.sync="AddUserDialogVisible"
      width="50%"
    >
      <el-form :model="AddUserForm" :rules="AddUserFormRules" ref="AddUserFormRef">
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="AddUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="AddUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddUserRequest">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      RolesList: [],
      RolesDialogVisible: false,
      RolesTreeData: [],
      RolesTreeProps: {
        label: "authName",
        children: "children"
      },
      checkedKeys: [],
      UserId: "",
      EditUserDialogVisible: false,
      EditUserForm: {},
      EditUserFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" }
        ]
      },
      AddUserDialogVisible: false,
      AddUserForm: {},
      AddUserFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.RolesList = res.data;
    },
    async handleRemoveRoles(row, rightId) {
      try {
        const confirm = await this.$confirm("确认删除该权限?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        if (confirm === "confirm") {
          const { data: res } = await this.$http.delete(
            `roles/${row.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) return this.$message.error("操作失败");
          row.children = res.data;
        }
      } catch (error) {
        this.$message.info("已取消删除");
      }
    },
    showRolesDialog(role) {
      this.UserId = role.id;
      this.getRolesTreeData();
      this.getcheckedKeys(role, this.checkedKeys);
      this.RolesDialogVisible = true;
    },
    async getRolesTreeData() {
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) return this.$message.error("操作失败");
      this.RolesTreeData = res.data;
    },
    getcheckedKeys(node, keys) {
      if (!node.children) {
        return keys.push(node.id);
      }
      node.children.forEach(element => {
        this.getcheckedKeys(element, keys);
      });
    },
    handleRolesDialogClose() {
      this.checkedKeys = [];
    },
    async handleGiveRolesRequest() {
      const KeysID = [
        ...this.$refs.TreeRef.getCheckedKeys(),
        ...this.$refs.TreeRef.getHalfCheckedKeys()
      ];
      const strKeysID = KeysID.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.UserId}/rights`,
        { rids: strKeysID }
      );
      if (res.meta.status !== 200) return this.$message.error("操作失败");
      this.$message.success(res.meta.msg);
      this.getRolesList();
      this.RolesDialogVisible = false;
    },
    async getEditUserInfo(id) {
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) return this.$message.error("操作失败");
      this.EditUserForm = res.data;
      this.EditUserDialogVisible = true;
      this.UserId = id;
    },
    handleEditFormReset() {
      this.$refs.EditUserFormRef.resetFields();
    },
    handleEditUserRequest() {
      this.$refs.EditUserFormRef.validate(async value => {
        if (!value) {
          return;
        }
        const { data: res } = await this.$http.put(`roles/${this.UserId}`, {
          roleName: this.EditUserForm.roleName,
          roleDesc: this.EditUserForm.roleDesc
        });
        if (res.meta.status !== 200) return this.$message.error("操作失败");
        this.$message.success("修改成功");
        this.getRolesList();
        this.EditUserDialogVisible = false;
      });
    },
    handleAddFormReset() {
      this.$refs.AddUserFormRef.resetFields();
    },
    showAddUserDialog() {
      this.AddUserDialogVisible = true;
    },
    handleAddUserRequest() {
      this.$refs.AddUserFormRef.validate(async value => {
        if (!value) {
          return;
        }
        const { data: res } = await this.$http.post("roles", {
          roleName: this.AddUserForm.roleName,
          roleDesc: this.AddUserForm.roleDesc
        });
        if (res.meta.status !== 201) return this.$message.error("操作失败");
        this.$message.success("添加成功");
        this.getRolesList();
        this.AddUserDialogVisible = false;
      });
    },
    async handleRemoveUser(id) {
      try {
        const confirm = await this.$confirm("确认删除该角色吗?", "提示", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        });
        if (confirm == "confirm") {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg);
          this.getRolesList();
        }
      } catch (error) {
        this.$message.info("已取消删除");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin-right: 20px;
}
.MarginBottom {
  margin-bottom: 10px;
}
.el-row {
  padding: 10px 0;
}

.borderBottom {
  border-bottom: 1px solid #eee;
}
.borderTop {
  border-top: 1px solid #eee;
}
.center_col {
  display: flex;
  align-items: center;
}
</style>